# coding:utf-8
from myapp import db
from datetime import datetime

#角色资源关联表
role_resource_table = db.Table('sys_role_resource', db.metadata,
                               db.Column('role_id', db.String, db.ForeignKey('sys_role.id')),
                               db.Column('resource_id', db.String, db.ForeignKey('sys_resource.id')))

role_organization_table = db.Table('sys_role_organization', db.metadata,
                               db.Column('role_id', db.String, db.ForeignKey('sys_role.id')),
                               db.Column('organization_id', db.String, db.ForeignKey('sys_organization.id')))

class Role(db.Model):
    __tablename__ = 'sys_role'
    id = db.Column(db.Integer, primary_key=True)
    create_time = db.Column(db.DateTime, index=True, default=datetime.now)
    update_time = db.Column(db.DateTime, index=True, default=datetime.now)
    name = db.Column(db.String(100))
    description = db.Column(db.String(200))
    iconcls = db.Column(db.String(100))
    seq = db.Column(db.Integer)
    role_key = db.Column(db.String(100))
    datascope = db.Column(db.Integer)
    status = db.Column(db.String(10))

    #包含资源
    resources = db.relationship('Resource',
                                secondary=role_resource_table,
                                backref=db.backref('roles', lazy='dynamic')) #资源所属角色

    #包含部门
    depts = db.relationship('Organization',
                                secondary=role_organization_table,
                                backref=db.backref('roles', lazy='dynamic')) #部门所属角色

    def get_id(self):
        return str(self.ID)

    def to_dict(self):
        return dict([(k, getattr(self, k)) for k in self.__dict__.keys() if not k.startswith("_")])

    def __repr__(self):
        return '<Role name:%r description:%r iconCls:%r seq:%r>\n'  \
             %(self.name, self.description, self.iconcls, self.seq)

    def to_json(self):
        json = {
            'roleId': self.id,
            'createTime': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'updateTime': self.update_time.strftime('%Y-%m-%d %H:%M:%S'),
            'roleName': self.name,
            'remark': self.description,
            'iconCls': self.iconcls,
            'roleSort': self.seq,
            'status': self.status,
            'roleKey': self.role_key,
            'dataScope': self.datascope
        }

        
        if hasattr(self, 'flag'):
            json['flag'] = self.flag

        return json
